import React, { Component } from 'react';
import { Modal, message, Form, Input, Select } from 'antd';
import PropTypes from 'prop-types';
import { batchUpdateAssets } from '@api/asset';
import cn from 'classnames';
import CheckboxSelect from '@components/checkbox-select';
import _ from 'lodash';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import './index.less';
class BatchEditAttrModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      selectedOptions: {}
    };
  }

  static propTypes = {
    siteIds: PropTypes.array,
    sites: PropTypes.array,
    loadAssets: PropTypes.func,
    visible: PropTypes.bool,
    onClose: PropTypes.func,
    organizationTree: PropTypes.array,
    onOrgPopupVisibleChange: PropTypes.func,
    role: PropTypes.string,
    customList: PropTypes.array,
    form: PropTypes.object
  };

  customSelect = (dataSoure, ismMultiple) => (
    <Select
      {...(ismMultiple ? { mode: 'multiple' } : {})}
      allowClear
      dropdownClassName="add-asset-modal-url-prefix"
      style={{ width: '100%' }}
      placeholder="请选择"
    >
      {dataSoure.map(optionItem => (
        <Select.Option key={optionItem} value={optionItem}>
          {optionItem}
        </Select.Option>
      ))}
    </Select>
  );

  renderCustomList = () => {
    const {
      customList,
      form: { getFieldDecorator },
      visible
    } = this.props;
    const { selectedOptions } = this.state;
    return visible
      ? customList.map(item => {
          return (
            <div key={item.name} className={cn('item', 'ip-wrapper')}>
              <span className="name">{item.name}</span>
              <Form.Item>
                {getFieldDecorator(item._id, {
                  initialValue: []
                })(
                  item.type === 'string' ? (
                    <Input placeholder="请输入中文、英文、特殊字符或者数字，不超过32个字符" />
                  ) : item.type === 'single' ? (
                    this.customSelect(_.get(item, 'options', []), false)
                  ) : item.type === 'multiple' ? (
                    <CheckboxSelect
                      boxHeight={100}
                      className="plugins"
                      placeholder="请输入选项名称进行搜索"
                      options={_.get(item, 'options', []).map(item => {
                        return {
                          key: item,
                          value: item
                        };
                      })}
                      optionKey="key"
                      namePath="value"
                      selected={selectedOptions[item.name] || []}
                      onChange={keys => {
                        this.setState({
                          selectedOptions: {
                            ...this.state.selectedOptions,
                            [item.name]: keys
                          }
                        });
                      }}
                      allButton={false}
                    />
                  ) : null
                )}
              </Form.Item>
            </div>
          );
        })
      : null;
  };

  onOk = () => {
    const {
      form: { validateFields },
      siteIds,
      onClose,
      loadAssets
    } = this.props;
    validateFields((errors, values) => {
      if (errors) {
        return;
      }
      // 处理自定义属性
      let customAttributes = [];
      _.forIn(values, (value, key) => {
        customAttributes.push({
          attributeOid: key,
          value: [].concat(value)
        });
      });

      if (_.isEmpty(customAttributes)) {
        message.warn('请至少填写一个自定义属性');
        return;
      }
      this.setState({ loading: true });
      batchUpdateAssets({ query: { siteIds }, set: { customAttributes } })
        .then(() => {
          message.success('批量设置自定义属性成功!');
          this.setState({ loading: false });
          onClose();
          loadAssets();
        })
        .catch(() => {
          message.error('批量设置自定义属性失败!');
          this.setState({ loading: false });
        });
    });
  };

  render() {
    const { visible, onClose, role, customList } = this.props;
    const { loading } = this.state;

    return (
      <Modal
        maskClosable={false}
        visible={visible}
        title="自定义属性"
        onCancel={() => {
          this.setState({ selectedOptions: {} });
          onClose();
        }}
        className={cn(
          'batch-edit-attr-modal',
          'no-header-bottom-lines',
          'bottom-center',
          'padding-24'
        )}
        onOk={this.onOk}
        confirmLoading={loading}
      >
        <div className="content">
          {Boolean(customList.length) && this.renderCustomList()}
          {role === '安全管理员' ? (
            <Link
              to="/asset-config/attribute-config"
              style={{ marginLeft: '76px' }}
              target="_blank"
            >
              进行资产属性配置
            </Link>
          ) : (
            <p style={{ marginLeft: '76px', color: '#0b6fd6' }}>可联系管理员增加更多资产属性</p>
          )}
        </div>
      </Modal>
    );
  }
}

const mapStateToProps = state => {
  return {
    role: _.get(state, 'auth.user.role', '')
  };
};

export default connect(mapStateToProps)(Form.create()(BatchEditAttrModal));
